import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _isFunction from "lodash/isFunction";
import { mapCustomize } from "../utils/customize";
/**
 * 如果 存在 则加载
 * 否则 返回 null
 * @param IMCode
 * @return {Promise<null|*>}
 */

export function loadIMAsync(_x) {
  return _loadIMAsync.apply(this, arguments);
}

function _loadIMAsync() {
  _loadIMAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(IMCode) {
    var layout, IM;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!mapCustomize.has({
              module: 'cpaas-front-cims',
              feature: 'IM',
              key: IMCode
            })) {
              _context.next = 7;
              break;
            }

            layout = mapCustomize.get({
              module: 'cpaas-front-cims',
              feature: 'IM',
              key: IMCode
            });

            if (!_isFunction(layout && layout.component)) {
              _context.next = 7;
              break;
            }

            _context.next = 5;
            return layout.component();

          case 5:
            IM = _context.sent;
            return _context.abrupt("return", IM);

          case 7:
            return _context.abrupt("return", null);

          case 8:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _loadIMAsync.apply(this, arguments);
}

export function setIM(IMConfig) {
  // TODO: 判断是否需要检查 重复设置的问题
  mapCustomize.set({
    module: 'cpaas-front-cims',
    feature: 'IM',
    key: IMConfig.code,
    data: {
      component: IMConfig.component
    }
  });
}
/**
 * 监听 IM 变化
 * @param listener 监听器
 * @param initRun 第一次是否允许监听器
 */

export function watchIMSetComponent(listener, initRun) {
  if (initRun) {
    listener();
  }

  var mListener = function mListener() {
    var setObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var module = setObj.module,
        feature = setObj.feature;

    if (module === 'cpaas-front-cims' && feature === 'IM') {
      listener(setObj);
      mapCustomize.off('set', mListener);
    }
  };

  mapCustomize.on('set', mListener);

  var unListener = function unListener() {
    mapCustomize.off('set', mListener);
  };

  return unListener;
}